﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Eqwww.Domain.Models.SystemSecurity;
using Eqwww.App.SystemSecurity;
using Eqwww.Code;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.StaticFiles;
using Eqwww.App.Authorize;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.Config;

namespace Eqwww.Web.Areas.SystemSecurity.Controllers
{
    [Area("SystemSecurity")]
    public class DbBackupController : ControllerBase
    {
        private IWebHostEnvironment _env;
        private DbBackupApp _app;
        private AuthorizeApp _authorizeApp;
        private IDbBackupConfigProvider _dbBackupConfigProvider;
        public DbBackupController(DbBackupApp app, IWebHostEnvironment env
            ,AuthorizeApp authorizeApp
            , IDbBackupConfigProvider dbBackupConfigProvider)
        {
            _env = env;
            _app = app;
            _authorizeApp = authorizeApp;
            _dbBackupConfigProvider = dbBackupConfigProvider;
        }
        public IActionResult Index()
        {
            var currentModuleCode = "SystemSecurity_DbBackup";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        public IActionResult IndexGridJson(Pagination pagination)
        {
            var rows = _app.GetList(pagination);
            var data = new
            {
                rows = rows,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [AuthFilter]
        public IActionResult Create()
        {
            var config = _dbBackupConfigProvider.Load();
            if (config.UseCustomBackupDatabaseName)
            {
                if (string.IsNullOrEmpty(config.CustomBackupDatabaseName))
                    return ErrorView("数据备份配置中指定了使用自定义数据库,但未设置数据库名称。");
                else
                    ViewData["DbName"] = config.CustomBackupDatabaseName;
            }
            else
            {
                ViewData["DbName"] = _app.LoadDefaultDatabaseName();
            }
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult CreateSubmit([Bind("FileName,DbName")] DbBackupModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(Common.ModelStateErrorResult(ModelState));
            }
            model.FilePath = _env.WebRootPath + System.IO.Path.Combine(@"\upload\dbbackup\" + model.FileName + ".bak");
            model.FileName = model.FileName + ".bak";
            model.DbBackupType = DbBackupType.Manual;
            _app.Create(model);
            return Success("操作成功！");
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteSubmit(string id)
        {
            var model = _app.Get(id);
            
            _app.Delete(id);
            return Success("操作成功！");
        }

        [ExceptionFilter]
        public IActionResult DownLoad(string id)
        {
            var att = _app.Get(id);
            var path = System.IO.Path.Combine(_env.WebRootPath + att.FilePath);
            
                var stream = System.IO.File.OpenRead(path);
                string fileExt = "." + att.FileName.Split('.')[1].ToLower();
                //获取文件的ContentType
                var provider = new FileExtensionContentTypeProvider();
                provider.Mappings[".bak"] = "application/x-msdownload";
                var memi = provider.Mappings[fileExt];

                return File(stream, memi, att.FileName);
                //return File(stream, memi, Path.GetFileName(addrUrl));
            
        }

        [AuthFilter]
        public IActionResult Config()
        {
            var model = _dbBackupConfigProvider.Load();
            return View(model);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ConfigSubmit(DbBackupConfig model)
        {
            if (ModelState.IsValid)
            {
                _dbBackupConfigProvider.Save(model);
                return Success("操作成功!");
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }

    }
}